package com.edu.whty.controller;

import com.edu.whty.common.constants.CodeConstants;
import com.edu.whty.common.tools.ResponseMessage;
import com.edu.whty.common.tools.StringUtil;
import com.edu.whty.entity.base.CloudPage;
import com.edu.whty.entity.base.PageList;
import com.edu.whty.entity.base.ResponseEntity;
import com.edu.whty.entity.cloud.TbTeachingRes;
import com.edu.whty.entity.cloud.TbTeachingResPackage;
import com.edu.whty.entity.cloud.TeachingResPackageReq;
import com.edu.whty.entity.cloud.TeachingResReq;
import com.edu.whty.entity.comment.CommentsReq;
import com.edu.whty.entity.school.RepoCatalogResource;
import com.edu.whty.service.TeachingResService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/teachingRes")
public class TeachingResController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private TeachingResService teachingResService;

    @RequestMapping(value = "/addComment", method = RequestMethod.POST)
    public ResponseEntity addComment(HttpServletRequest request, HttpServletResponse response,
                                     @RequestBody CommentsReq comments) {
        try {
            if (null == comments) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "参数不能为空");
            } else {
                if (StringUtils.isEmpty(comments.getUserId())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "userId不能为空");
                }
                if (StringUtils.isEmpty(comments.getPlatformCode())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "platformCode不能为空");
                }
                if (StringUtils.isEmpty(comments.getBusinessId())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "businessId不能为空");
                }
                if (StringUtils.isEmpty(comments.getBusinessType())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "businessType不能为空");
                }
                if (comments.getContents() == null || comments.getContents().size() == 0) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "contents不能为空");
                }
                if (null == comments.getScore()) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "score不能为空");
                } else if (null != comments.getScore() && (comments.getScore() < 1 || comments.getScore() > 5)) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "score只能取1到5");
                }
                if (StringUtils.isEmpty(comments.getType())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "type不能为空");
                }
                if (comments.getType().trim().equals("2")) {
                    //发表回复时的必填字段
                    if (StringUtils.isEmpty(comments.getReplyedCommentId())) {
                        return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "replyedCommentId不能为空");
                    }
                    if (StringUtils.isEmpty(comments.getReplyedUserId())) {
                        return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "replyedUserId不能为空");
                    }
                    if (StringUtils.isEmpty(comments.getReplyedRealName())) {
                        return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "replyedRealName不能为空");
                    }
                }

                String netIp = null == request.getAttribute("netIp") ? null : request.getAttribute("netIp").toString();
                Map<String, Object> map = teachingResService.addComment(comments, netIp);

                return ResponseEntity.getSuccessResponse(map);
            }
        } catch (Exception e) {
            // 捕捉异常构造返回信息
            logger.error("添加评论发生异常" + e.getMessage(), e);
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "添加评论发生异常");
        }
    }

    @RequestMapping(value = "/getComment", method = RequestMethod.POST)
    public ResponseEntity getComment(HttpServletRequest request, HttpServletResponse response,
                                     @RequestBody CommentsReq commentsReq) {
        try {
            if (null == commentsReq) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "参数不能为空");
            } else {
                if (StringUtils.isEmpty(commentsReq.getUserId())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "userId不能为空");
                }
                if (StringUtils.isEmpty(commentsReq.getBusinessId())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "businessId不能为空");
                }

                List<Map<String, Object>> commentsList = teachingResService.getComment(commentsReq);

                return ResponseEntity.getSuccessResponse(commentsList);
            }
        } catch (Exception e) {
            logger.error("查询评论发生异常" + e.getMessage(), e);
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "查询评论发生异常");
        }
    }

    @RequestMapping(value = "/statComments", method = RequestMethod.POST)
    public ResponseEntity statComments(HttpServletRequest request, HttpServletResponse response,
                                     @RequestBody CommentsReq commentsReq) {
        try {
            if (null == commentsReq) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "参数不能为空");
            } else {
                if (StringUtils.isEmpty(commentsReq.getBusinessId())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "businessId不能为空");
                }

                List<Map<String, Object>> commentsStatList = teachingResService.statComments(commentsReq);

                return ResponseEntity.getSuccessResponse(commentsStatList);
            }
        } catch (Exception e) {
            logger.error("统计评论发生异常" + e.getMessage(), e);
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "统计评论发生异常");
        }
    }

    @RequestMapping(value = "/ysykBagPageList", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity ysykBagPageList(HttpServletRequest request, HttpServletResponse response, @RequestBody TeachingResPackageReq teachingResPackageReq) {
        try {
            if (null == teachingResPackageReq) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "参数不能为空");
            } else {
                if (null == teachingResPackageReq.getUserId() || StringUtil.isEmpty(teachingResPackageReq.getUserId())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "userId 必须传");

                }
                if (null == teachingResPackageReq.getChapterId() || StringUtil.isEmpty(teachingResPackageReq.getChapterId())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "chapterId 必须传");

                }
            }
            //从request 获取当前登录的登录平台编码
            PageList<TbTeachingResPackage> pageList = teachingResService.ysykBagPageList(teachingResPackageReq);
            return ResponseEntity.getSuccessResponse(pageList);

        } catch (Exception e) {
            // 捕捉异常构造返回信息
            logger.error("一师一优课资源包列表发生异常" + e.getMessage(), e);
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, e.getMessage());
        }
    }


    @RequestMapping(value = "/teachingResPageList", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity teachingResPageList(HttpServletRequest request, HttpServletResponse response,
                                              @RequestBody TeachingResReq teachingResReq) {
        try {
            if (null == teachingResReq) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "参数不能为空");
            } else {
                if (null == teachingResReq.getResType()) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "resType必须传");
                }

            }
            //从request 获取当前登录的登录平台编码
            CloudPage<TbTeachingRes> pageList = teachingResService.teachingResPageList(teachingResReq);
            return ResponseEntity.getSuccessResponse(pageList);
        } catch (Exception e) {
            // 捕捉异常构造返回信息
            logger.error("教学资源分页查询发生异常" + e.getMessage(), e);
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, e.getMessage().toString());
        }
    }


    /**
     *
     * @param bean
     * @return 修改下载量
     */
    @RequestMapping(value = "/modResPvByResId", method = RequestMethod.POST)
    @ResponseBody
    public ResponseMessage modResPvByResId(@RequestBody TeachingResReq bean)  {
        ResponseMessage message = ResponseMessage.getSuccessResponse();
        String sourcePackageId = bean.getSourcePackageId();
        Integer pkid = bean.getPkid();
        logger.info("modResPvByResId.sourcePackageId="+sourcePackageId+"--pkid="+pkid);
        try {
            TbTeachingRes resource = new TbTeachingRes();
            if(pkid!=null && pkid>0){
                TbTeachingRes param = new TbTeachingRes();
                param.setId(pkid+"");
//                param.setSourcePackageId(sourcePackageId);
                resource = teachingResService.getTeachingResById(param);
                if (resource == null) {
                    ResponseMessage responseMessage = ResponseMessage.getFailedResponse();
                    responseMessage.setResultDesc("resource does not exists");
                    return responseMessage;
                }
            }

            // 修改下载次数,下载次数
            TbTeachingRes upRes = new TbTeachingRes();
            int downCount = resource.getDownCount();
            if (downCount == 0) {
                downCount = 1;
            } else {
                downCount++;
            }
            upRes.setDownCount(downCount);
            upRes.setViewCount(resource.getViewCount());
            upRes.setId(pkid+"");
            teachingResService.modTeachingResById(upRes);
            resource.setDownCount(downCount);

        }catch (Exception e){
            logger.error("updateRepoRes modResPvByResId",e);
        }
        return message;
    }




    @RequestMapping(value = "/jpzyResPageList", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity jpzyResPageList(HttpServletRequest request, HttpServletResponse response,
                                              @RequestBody TeachingResReq teachingResReq) {
        try {
            teachingResReq.setResType("5");
            if (null == teachingResReq) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "参数不能为空");
            } else {
                if (null == teachingResReq.getChapterId()) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "chapterId必须传");
                }
            }
            //从request 获取当前登录的登录平台编码
            CloudPage<TbTeachingRes> pageList = teachingResService.jpzyResPageList(teachingResReq);
            return ResponseEntity.getSuccessResponse(pageList);
        } catch (Exception e) {
            // 捕捉异常构造返回信息
            logger.error("教学资源分页查询发生异常" + e.getMessage(), e);
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, e.getMessage().toString());
        }
    }

    /**
     *
     * @author sun
     * @Date 创建时间  2020年8月3日下午4:39:22
     * @Title: recommendResList
     * @Description: TODO(评分次数,评论次数,点赞次数等业务数据加1)
     * @param @param request
     * @throws
     */
    @RequestMapping(value = "/timesPlusOneById", method = RequestMethod.POST )
    @ResponseBody
    public ResponseEntity timesPlusOneById(HttpServletRequest request, HttpServletResponse response,
                                 @RequestBody Map<String, Object> map){
        try {
            if(null == map){
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "参数不能为空");

            }else {
                if((!map.containsKey("id")|| org.apache.commons.lang.StringUtils.isEmpty(map.get("id").toString()))){
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "id 不能为空");
                }
                if(!map.containsKey("userId")|| org.apache.commons.lang.StringUtils.isEmpty(map.get("userId").toString())){
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "userId 不能为空");
                }
//                if(!map.containsKey("userName")|| org.apache.commons.lang.StringUtils.isEmpty(map.get("userName").toString())){
//                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "userName 不能为空");
//                }
//                if(!map.containsKey("platformCode")|| org.apache.commons.lang.StringUtils.isEmpty(map.get("platformCode").toString())){
//                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "platformCode 不能为空");
//                }
//                if(!map.containsKey("resType")|| org.apache.commons.lang.StringUtils.isEmpty(map.get("resType").toString())){
//                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "resType 不能为空");
//                }
            }

            teachingResService.timesPlusOneById(map);
            return ResponseEntity.getSuccessResponse();
        }  catch (Exception e) {
            // 捕捉异常构造返回信息
            logger.error("教学资源评分次数,评论次数,点赞次数等业务数据加1发生异常"+e.getMessage(), e);
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "发生异常");

        }
    }
}